package com.stedu.controller;

import com.stedu.bean.Book;
import com.stedu.bean.Classify;
import com.stedu.bean.ClassifyWithBookCount;
import com.stedu.bean.RespBean;
import com.stedu.exception.SteduException;
import com.stedu.service.ClassifyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/admin/classify")
public class ClassifyController {
    @Autowired
    private ClassifyService classifyService;

    @PostMapping
    public RespBean insertController(@RequestBody Classify classify) throws SteduException {
        if (classifyService.insertClassify(classify)){
            return RespBean.ok("添加成功");
        }else{
            return RespBean.error("添加失败");
        }
    }

    @PutMapping
    public RespBean updateController(@RequestBody Classify classify){
        if (classifyService.updateClassify(classify)){
            return RespBean.ok("修改成功");
        }else{
            return RespBean.error("修改失败");
        }
    }

    @DeleteMapping("/{cid}")
    public RespBean deleteController(@PathVariable Integer cid){
        if (classifyService.deleteClassify(cid)){
            return RespBean.ok("删除成功");
        }else {
            return RespBean.error("删除失败");
        }
    }

    @GetMapping
    public RespBean selectAllController(){
        List<Book> classifies = classifyService.selectAll();
        return RespBean.ok("查询成功", classifies);
    }

    @GetMapping("/{cname}")
    public RespBean selectBidAndCid(@PathVariable String cname){
        Classify classify = classifyService.selectCname(cname);
        return RespBean.ok("查询成功", classify);
    }

    @GetMapping("/byIdAndName/{cid}/{cname}")
    public RespBean selectByIdAndName(@PathVariable Integer cid, @PathVariable String cname) {
        ClassifyWithBookCount classify = classifyService.selectByIdAndName(cid, cname);
        if (classify!= null) {
            return RespBean.ok("查询成功", classify);
        } else {
            return RespBean.error("查询失败");
        }
    }

    @GetMapping("/CB")
    public RespBean selectCAndB(@RequestBody String cname){
        if (classifyService.selectBookWithClassifies(cname) != null){
            Classify classify = classifyService.selectBookWithClassifies(cname);
            return RespBean.ok("查询成功", classify);
        }else{
            return RespBean.error("查询失败，没有该用户ID");
        }
    }

}
